﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace SweeperPrototype.Objects
{
    public class NotifyList<T_VALUE> : INotifyList<T_VALUE>
    {
        public NotifyList()
        {
            m_Items = new List<T_VALUE>();
        }
        
        private readonly List<T_VALUE> m_Items;

        public IEnumerable<T_VALUE> Items
        {
            get { return m_Items; }
        }

        public int Count { get { return m_Items.Count; } }
        public void Add( T_VALUE item )
        {
            m_Items.Add(item);
            Addition(item, m_Items.Count );
        }

        public void Add(T_VALUE addition, int index)
        {
            if( index < m_Items.Count )
            {
                m_Items.Insert( index, addition );
                Addition( addition, index );
            }
            else
            {
                m_Items.Add(addition);
                Addition(addition, m_Items.Count - 1);
            }
        }

        public void Remove( T_VALUE item )
        {
            // TODO: performance suck.
            int index = m_Items.IndexOf(item);
            if (index == -1) {
                throw new Exception("Potential multithreading exception");
                //return; 
            }
            Remove( item, index );
        }

        public void Remove( T_VALUE item, int index)
        {
            m_Items.RemoveAt(index);
            Removal(item, index);
        }

        public void Remove(int index)
        {
            Remove(m_Items[index], index);
        }

        public T_VALUE this[int index]
        {
            get { return m_Items[index]; }
        }

        public event AdditionNotice<T_VALUE> Addition = delegate { };
        public event RemovalNotice<T_VALUE> Removal = delegate { };
        public event Action Cleared = delegate { }; 
        
        
        public void Clear()
        {
            m_Items.Clear();
        }
        #region Implementation of IEnumerable

        public IEnumerator<T_VALUE> GetEnumerator()
        {
            return m_Items.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion

    }
    
    public delegate void AdditionNotice<T>(T addition, int index);
    public delegate void RemovalNotice<T>(T removal, int index);
}